package com.Master.service.Master.impl;

import com.Master.domain.Master.DTO.MasterDTO;
import com.Master.domain.Master.DTO.MasterRegDTO;
import com.Master.service.Master.MasterService;
import com.blog.security.service.TokenService;
import com.Master.domain.Master.MasterInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.comon.core.domain.result.R;
import com.comon.core.enums.ResultCode;
import com.comon.core.utils.BCryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.Master.mapper.MasterMapper;
/**
 * Created with Intellij IDEA.
 * Description;
 * User:TQ02
 * Data:2024-08-24
 * Time:15:26
 * Text：
 */
@Service
public class MasterServiceImpl implements MasterService {

    @Autowired
    MasterMapper masterMapper;
    @Autowired
    TokenService tokenService;



    @Value("${jwt.secret}")
    private String secret;

    public R<?> login(MasterDTO masterDTO){
        LambdaQueryWrapper<MasterInfo> queryWrapper = new LambdaQueryWrapper<>();
        MasterInfo user = masterMapper.selectOne(queryWrapper.select(MasterInfo::getUserId,MasterInfo::getPassword, MasterInfo::getUserName, MasterInfo::getIdentity).eq(MasterInfo::getPhone, masterDTO.getUserPhone()));
        if(user == null){
            return R.fail(ResultCode.FAILED_LOGIN);
        } else if (BCryptUtils.matchesPassword(masterDTO.getPassword(), user.getPassword())) {
            return R.ok("登陆成功",tokenService.createToken(user.getUserId(), user.getPhone(),secret,user.getUserName(),user.getIdentity()));
        }
        return null;
    }

    @Override
    public R<?> reg(MasterRegDTO regInfo) {
        MasterInfo masterInfo = new MasterInfo();
        masterInfo.setIdentity(regInfo.getIdentity());
        masterInfo.setSex(regInfo.getSex());
        masterInfo.setPhone(regInfo.getPhone());
        masterInfo.setPassword(BCryptUtils.encryptPassword(regInfo.getPassword()));
        masterInfo.setPhoto(regInfo.getPhoto());
        masterInfo.setUserName(regInfo.getUserName());

        int i = masterMapper.insert(masterInfo);
        return i == 1? R.ok("注册成功"):R.fail("电话已存在");
    }

}
